<template>
  <div class="content">
    <div class="top flex-column">
      <!-- <transition name='fade'> -->
      <div class="tabs flex-row">
        <!-- 动态绑定active类名 -->
        <div class="tab active">
          手机验证
        </div>
      </div>
      <!-- </transition> -->
    </div>
    <div class="form-login">
      <div class="form-content">
        <van-field v-model="loginForm.phone" label="手机号" placeholder="请输入手机号码" />
      </div>
      <div class="form-content">
        <van-field v-model="loginForm.verifyCode" label="验证码" placeholder="请输入验证码">
          <template #button>
            <div class="btn" @click="getCode()">{{ codeMesg }}</div>
          </template>
        </van-field>
      </div>
    </div>
    <div class="foot">
      <div class="log_btn" @click="handleVerify()">确定</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import router from "@/router";
import { showToast } from "vant";
import { userStore } from "@/store/userInfo";
import { getSms, verifySms } from "@/api/loginApi";
const {userInfo} = userStore();
const loginForm = ref({
  phone: "",
  verifyCode: "",
});
// 手机号回显
if(userInfo.phone) {
  loginForm.value.phone = userInfo.phone;
} 
const codeMesg = ref("发送验证码");
const sendType = ref(true);
// 获取验证码前校验
const verfyPhone = () => {
  const phoneReg = /^1[3-9]\d{9}$/;
  if (phoneReg.test(loginForm.value.phone)) {
    return true;
  } else {
    showToast("请输入正确的手机号码");
  }
};
// 获取验证码
const getSmsNum = async () => {
  const { phone } = loginForm.value;
  const res = await getSms({
    phone,
    scene: "LOGIN",
  });
  if (res && res.code == 200) {
    showToast("短信发送成功");
  }
};
const getCode = () => {
  // 发送验证码
  if (sendType.value && verfyPhone()) {
    sendType.value = false;
    getSmsNum();
    codeMesg.value = "60秒后重新发送";
    let time = 59;
    let timer = setInterval(() => {
      if (time == 0) {
        clearInterval(timer);
        codeMesg.value = "重新发送";
        sendType.value = true;
      } else {
        codeMesg.value = time + "秒后重新发送";
        time--;
      }
    }, 1000);
  }
};
// 点击确定
const handleVerify = async () => {
  if(loginForm.value.phone.length && loginForm.value.verifyCode.length) {
    const params = {
    phone: loginForm.value.phone,
    code: loginForm.value.verifyCode,
    scene: 'LOGIN'
    }
  await verifySms(params);
    router.push({path:'/change-password',query:params})
    showToast("手机号验证成功");
    // console.log(params);
  }else {
    showToast("请填写手机号和验证码");
  }
  }
  
</script>

<style lang="less" scoped>
  @import "./login.less";
  .foot {
  margin-top: 100px;
}
</style>